#!/bin/bash

# 智能门禁系统部署前安全检查脚本
# Usage: ./deploy_check.sh [environment]
# Example: ./deploy_check.sh production

set -e  # Exit on any error

ENVIRONMENT=${1:-development}
ENV_FILE=".env"

echo "🚀 智能门禁系统部署前检查"
echo "=================================="
echo "环境: $ENVIRONMENT"
echo "时间: $(date)"
echo ""

# 检查环境文件
if [ "$ENVIRONMENT" = "production" ]; then
    ENV_FILE=".env.production"
fi

if [ ! -f "$ENV_FILE" ]; then
    echo "❌ 环境文件 $ENV_FILE 不存在!"
    echo "请复制相应的模板文件并配置:"
    if [ "$ENVIRONMENT" = "production" ]; then
        echo "cp .env.production.example .env.production"
    else
        echo "cp .env.example .env"
    fi
    exit 1
fi

echo "✅ 环境文件 $ENV_FILE 存在"

# 激活虚拟环境
if [ -d "venv" ]; then
    echo "🐍 激活Python虚拟环境..."
    source venv/bin/activate
else
    echo "❌ 虚拟环境不存在! 请先创建虚拟环境:"
    echo "python3 -m venv venv"
    echo "source venv/bin/activate"
    echo "pip install -r requirements.txt"
    exit 1
fi

# 检查依赖
echo "📦 检查Python依赖..."
pip check

# 运行自定义安全检查
echo ""
echo "🔐 运行安全配置检查..."
if [ "$ENVIRONMENT" = "production" ]; then
    cp "$ENV_FILE" .env
fi

python check_security.py

# 运行Django内置检查
echo ""
echo "🔍 运行Django系统检查..."
if [ "$ENVIRONMENT" = "production" ]; then
    python manage.py check --deploy
else
    python manage.py check
fi

# 检查数据库迁移
echo ""
echo "💾 检查数据库迁移状态..."
python manage.py showmigrations

# 测试导入
echo ""
echo "🧪 测试关键模块导入..."
python -c "
try:
    import django
    import deepface
    import channels
    print('✅ 所有关键模块导入成功')
except ImportError as e:
    print(f'❌ 模块导入失败: {e}')
    exit(1)
"

# 生产环境额外检查
if [ "$ENVIRONMENT" = "production" ]; then
    echo ""
    echo "🏭 生产环境额外检查..."
    
    # 检查静态文件
    echo "📁 检查静态文件配置..."
    python manage.py collectstatic --dry-run --noinput
    
    # 检查日志目录
    if [ ! -d "logs" ]; then
        echo "📝 创建日志目录..."
        mkdir -p logs
    fi
    echo "✅ 日志目录存在"
    
    # 检查媒体目录权限
    if [ -d "media" ]; then
        echo "✅ 媒体目录存在"
    else
        echo "📁 创建媒体目录..."
        mkdir -p media
    fi
fi

echo ""
echo "=================================="
if [ "$ENVIRONMENT" = "production" ]; then
    echo "🎯 生产环境部署检查完成!"
    echo ""
    echo "📋 部署前最终确认清单:"
    echo "□ SECRET_KEY已更改为强密钥"
    echo "□ DEBUG设置为False"
    echo "□ ALLOWED_HOSTS配置正确的域名"
    echo "□ 数据库配置为生产数据库"
    echo "□ HTTPS和安全头已启用"
    echo "□ 防火墙和网络安全已配置"
    echo "□ 备份策略已制定"
    echo ""
    echo "🚀 如果所有检查都通过，可以开始部署!"
else
    echo "✅ 开发环境检查完成!"
    echo "可以启动开发服务器: python manage.py runserver"
fi

echo ""
echo "📚 更多信息请查看: SECURITY_SETUP.md"
